import {
    Card,
    Breadcrumb,
    Form,
    Button,
    Radio,
    Input,
    Upload,
    Space,
    Select,
    message
  } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useLocation, useSearchParams } from 'react-router-dom'
import './index.scss'
import { useEffect, useState } from 'react';
import { createArticleApi, editArticleApi, getArticleDetailApi } from '@/apis/article';
import { useChannel } from '@/hooks/useChannel';
  
  const Publish = () => {
    const channelListData = useChannel()
    const location = useLocation()
    const handleFinish = async (formData) => {
      // 校验文件数量是否与设置的数量一致
        if(imageType !== fileList.length){
            return message.error('图片数量不匹配')
        }
        let {channel_id, content, title, type=0} = formData
        let params = {
            title,
            channel_id,
            content,
            cover: {
                type,
                images: fileList.map(item=>item.url)
            }
        }
        // 新增文章逻辑
        if(!location.search){
          const res = createArticleApi(params)
          alert(res.message)
        }else{
          // 编辑文章逻辑
          params.id = location.search.split('id=')[1]
          const res = await editArticleApi(params)
          alert(res.message)
        }
    }
    const [fileList, setFileList] = useState([])
    // 上传成功回调
    const onUploadChange = info => {
      const fileList = info.fileList.map(file => {
        if (file.response) {
          return {
            url: file.response.data.url
          }
        }
        return file
      })
      setFileList(fileList)
    }
    // 切换radio事件，控制是否展示上传文件列表
    const [imageType, setImageType] = useState(0)
    const handleRadioChange = (e) => {
      setImageType(e.target.value)
    }
    // 获取form实例
    const [form] = Form.useForm()
    // 从路由拿到id参数，然后根据id请求文章详情数据，拿到文章详情后填充表单
    const [searchParams] = useSearchParams()
    const articleId = searchParams.get('id')
    useEffect(()=>{
    async function fetchData(){
      if(!articleId) return;
      await getArticleDetailApi(articleId).then(res=>{
        if(res){
          console.log(res.data, 'res.data')
          form.setFieldsValue({
            ...res.data,
            type: res.data.cover.type
          })
          setImageType(res.data.cover.type)
          setFileList(res.data.cover.images.map(item => ({url: item})))
        }
      })
    }
    fetchData()
    }, [articleId, form])
    return (
      <div className="publish">
        <Card
          title={
            <Breadcrumb separator=">" items={[{ title: <Link to="/home">首页</Link> }, { title: `${articleId?'编辑文章':'发布文章'}` }]}>
            </Breadcrumb>
          }
        >
          <Form
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ type: 0 }}
            onFinish={handleFinish}
            form={form}
          >
            <Form.Item
              label="标题"
              name="title"
              rules={[{ required: true, message: '请输入文章标题' }]}
            >
              <Input placeholder="请输入文章标题" style={{ width: 400 }} />
            </Form.Item>
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[{ required: true, message: '请选择文章频道' }]}
            >
              <Select placeholder="请选择文章频道" style={{ width: 400 }} options={channelListData}>
                {/* <Option value={0}>推荐</Option> */}
              </Select>
            </Form.Item>
  
            <Form.Item label="封面">
              <Form.Item name="type">
                <Radio.Group onChange={handleRadioChange}>
                  <Radio value={1}>单图</Radio>
                  <Radio value={3}>三图</Radio>
                  <Radio value={0}>无图</Radio>
                </Radio.Group>
              </Form.Item>
              {/* listType决定选择文件筐的外观样式
              showUploadList展示上传文件列表 */}
              {imageType > 0 && <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList
                action="http://geek.itheima.net/v1_0/upload"
                fileList={fileList}
                onChange={onUploadChange}
                maxCount={imageType}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>}
            </Form.Item>
            <Form.Item
              label="内容"
              name="content"
              rules={[{ required: true, message: '请输入文章内容' }]}
            >
                {/* 此处放置富文本编辑器，暂时用 textarea代替 */}
              <Input.TextArea
                placeholder="请输入文章内容"
                style={{ width: 600, height: 400 }}
              />
            </Form.Item>
  
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button size="large" type="primary" htmlType="submit">
                  发布文章
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
  
  export default Publish